import React from 'react';
import _ from 'lodash';
import classNames from 'classnames';
import { ITextValuePair, strEqual } from '../sys';

let dropdownBoxSeq = 0;

const nextDropdownBoxId = (): string => 'ddb' + (dropdownBoxSeq++);

interface IDropdownBoxGroupProps extends React.SelectHTMLAttributes<HTMLElement>, React.ClassAttributes<DropdownBox> {
    labelText?: string,
    options?: ITextValuePair[],
}

/**
 * 下拉框。通过定义`options`属性，创建一个下拉框框。`option.text`是下拉框的文本，`option.value`是下拉框的值。
 */
class DropdownBox extends React.Component<IDropdownBoxGroupProps> {
    private selectRef: React.RefObject<HTMLSelectElement>;

    constructor(props: IDropdownBoxGroupProps) {
        super(props);

        this.selectRef = React.createRef();
    }

    static defaultProps: IDropdownBoxGroupProps = {
        labelText: '',
        className: 'field',
    };

    getValue = (): string => {
        if (this.selectRef.current) {
            return this.selectRef.current.value;
        } else {
            return '';
        }
    }

    setValue = (value: any): DropdownBox => {
        const value_ = value ? value.toString() : '';
        if (this.selectRef.current) {
            this.selectRef.current.value = value_;
        }

        return this;
    };

    shouldComponentUpdate = (nextProps: IDropdownBoxGroupProps): boolean =>
        !_.isEqual(this.props.labelText, nextProps.labelText)
        || !_.isEqual(this.props.options, nextProps.options)
        || !_.isEqual(this.props.value, nextProps.value);

    render = (): JSX.Element => {
        const { labelText, className, value, options, ref, ...restProps } = this.props;
        const opts: JSX.Element[] = _.map(options, (entry: ITextValuePair) =>
            <option value={entry.value} key={entry.value} selected={strEqual(entry.value, value)} >{entry.text}</option>
        );
        return <div className={classNames(className)} >
            {labelText && (<label style={{ wordBreak: 'keep-all' }} >{labelText}</label>)}
            <select id={nextDropdownBoxId()} {...restProps}>
                {opts}
            </select>
        </div>;
    }
}

export { DropdownBox };